package leetcode_core.leetcode_1;

public class MinEatingSpeed {
    public int minEatingSpeed(int[] piles, int h) {
        int left =1,right=piles[getMaxIndex(piles)]+1;//定义搜索区间[left,right),right不可达
        while (left < right){
            int mid = left + (right-left)/2;
            if(canFinish(piles,mid,h)){
                right = mid;
            }else{
                left = mid+1;
            }
        }
        return left;
    }
    //O(N)
    private boolean canFinish(int[] piles,int speed,int h){
        int time = 0;
        for (int pile : piles) {
            time += timeOf(pile,speed);
        }
        return time<=h;
    }
    //以speed的速度吃香蕉,将要吃多久?
    private int timeOf(int n,int speed){
        return (n/speed)+((n%speed>0)?1:0);
    }
    private int getMaxIndex(int[] piles){
        int idx=0,max=Integer.MIN_VALUE;
        for(int i = 0;i<piles.length;i++){
            if(max<piles[i]){
                max = piles[i];
                idx = i;
            }
        }
        return idx;
    }

}
